<template>
  <!-- // 分配角色 -->
  <div>
    <!--  default-expand-all 默认展开
          show-checkbox 显示选择框
          check-strictly  设置true，关闭父子关联 -->
    <el-tree
      ref="treeRef"
      :data="permissionList"
      :props="{label : 'name'}"
      default-expand-all
      :show-checkbox="true"
      :check-strictly="true"
      node-key="id"
    />

    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="hSubmit">确定</el-button>
      <el-button @click="hClose">取消</el-button>
    </div>
  </div>
</template>
<script>
import { getPermissionList } from '@/api/permission'
import { tranListToTreeList } from '@/utils'
import { assignPerm, getRoleDetail } from '@/api/settings'
export default {
  props: {
    curId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      permissionList: [], // 存储权限数据
      permIds: []
    }
  },
  created() {
    this.loadPermissionList()
    this.loadRoleDetail()
  },
  methods: {
    async doSeve() {
      try {
        const permIds = this.$refs.treeRef.getCheckedKeys()
        console.log('permIds', permIds)
        // 获取选中的权限点
        const res = await assignPerm({ id: this.curId, permIds: permIds })
        console.log('assignPerm分配权限', res)
        this.$message.success(res.message)
        // 关闭弹层刷新数据
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 获取用户权限点
    async loadRoleDetail() {
      try {
        const { data: res } = await getRoleDetail(this.curId)
        console.log('getRoleDetail获取权限点', res)
        // 数据回填
        // this.permIds = res.permIds
        this.$refs.treeRef.setCheckedKeys(res.permIds)
      } catch (error) {
        console.log(error)
      }
    },
    // 获取所有的权限列表
    async loadPermissionList() {
      const res = await getPermissionList()
      console.log('getPermissionList权限列表数据', res)
      // 将平铺数据转化为树型数据
      this.permissionList = tranListToTreeList(res.data)
    },
    hSubmit() {
      // this.$emit('close')
      this.doSeve()
    },
    hClose() {
      this.$emit('success')
    }
  }
}
</script>
